package view {
    import flash.display.GradientType;
    import flash.geom.Matrix;

    import mx.core.UIComponent;

    public class Bar extends UIComponent {
        public var total:int;
        public var emergency:int;
        public var borderColor:uint = 0x52ABDF;
        public var borderThickness:Number = 0.5;
        public var bgColors:Array = [0x090300, 0x2c2c2d];
        public var normalColors:Array = [0x93dda9, 0x1bb84a];
        public var emergencyColors:Array = [0xf7aaa1, 0xed3824];
        public function Bar():void {
            super();
        }

        public function redraw(current:int):void {
            this.graphics.clear();
            // draw background
            this.graphics.lineStyle(borderThickness, borderColor, 0.4);
            drawGradient(this.height, this.width, bgColors, [0.6, 0.6]);

            if ((total <= 0) || (current <= 0)) return;
            if (current > total) current = total;
            //draw bar
            var barWidth:int = this.width / total * current;
            if (current > emergency) {
                drawGradient(this.height-1, barWidth, normalColors, [1, 1], 1);
            } else {
                drawGradient(this.height-1, barWidth, emergencyColors, [1, 1], 1);
            }
            this.graphics.endFill();
        }

        private function drawGradient(height:int, width:int, colors:Array, alphas:Array=null, y:int=0):void {
            if (alphas == null) alphas = [1, 1];
            var matr:Matrix = new Matrix();
            matr.createGradientBox(width, height, Math.PI/2, 0, 0);
            this.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, [0, 150], matr);
            this.graphics.drawRect(0, y, width, height);
        }
    }
}
